// FragmentEditVideo.java
package com.sadam.ui4.FragmentSelfPage;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.sadam.ui4.Data.Video;
import com.sadam.ui4.MainActivity;
import com.sadam.ui4.R;
import com.sadam.ui4.Data.MySqLiteOpenHelper;

public class FragmentEditVideo extends DialogFragment {

    private static final String ARG_VIDEO_ID = "video_id";

    private EditText etTitle, etDescription, etTags;
    private Button btnSave;
    private ImageButton btnBack;
    private ImageView ivVideoThumbnail;

    private long videoId;
    private Video video;
    private MySqLiteOpenHelper dbHelper;
    private MainActivity mainActivity;

    private OnVideoUpdatedListener onVideoUpdatedListener;

    public interface OnVideoUpdatedListener {
        void onVideoUpdated();
    }

    public void setOnVideoUpdatedListener(OnVideoUpdatedListener listener) {
        this.onVideoUpdatedListener = listener;
    }

    public static FragmentEditVideo newInstance(long videoId) {
        FragmentEditVideo fragment = new FragmentEditVideo();
        Bundle args = new Bundle();
        args.putLong(ARG_VIDEO_ID, videoId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.FullScreenDialogStyle);

        if (getArguments() != null) {
            videoId = getArguments().getLong(ARG_VIDEO_ID);
        }
    }

    @Override
    public void onAttach(@NonNull android.content.Context context) {
        super.onAttach(context);
        if (context instanceof MainActivity) {
            mainActivity = (MainActivity) context;
            dbHelper = mainActivity.getMySqLiteOpenHelper();
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_edit_video, container, false);
        initView(view);
        loadVideoData();
        return view;
    }

    private void initView(View view) {
        // 初始化视图组件
        btnBack = view.findViewById(R.id.iv_back);
        etTitle = view.findViewById(R.id.et_title);
        etDescription = view.findViewById(R.id.et_description);
        etTags = view.findViewById(R.id.et_tags);
        btnSave = view.findViewById(R.id.btn_publish);
        ivVideoThumbnail = view.findViewById(R.id.iv_add_content);

        // 修改按钮文字
        btnSave.setText("保存修改");

        // 隐藏添加内容的图片按钮（因为不能修改视频文件）
        ivVideoThumbnail.setVisibility(View.GONE);

        // 返回按钮点击事件
        btnBack.setOnClickListener(v -> dismiss());

        // 保存按钮点击事件
        btnSave.setOnClickListener(v -> saveVideoChanges());
    }

    // 在 FragmentEditVideo 中确保正确加载数据
    private void loadVideoData() {
        new Thread(() -> {
            try {
                video = dbHelper.getVideoById(videoId);
                if (video != null && getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        if (isAdded()) {
                            // 填充数据到表单
                            etTitle.setText(video.getTitle());
                            etDescription.setText(video.getDescription()); // 使用 getDescription()
                            etTags.setText(video.getTags()); // 使用 getTags()

                            Log.d("FragmentEditVideo", "加载视频数据成功: " + video.getTitle());
                        }
                    });
                } else {
                    Log.e("FragmentEditVideo", "未找到视频数据，ID: " + videoId);
                    if (getActivity() != null) {
                        getActivity().runOnUiThread(() ->
                                Toast.makeText(getContext(), "加载视频数据失败", Toast.LENGTH_SHORT).show());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() ->
                            Toast.makeText(getContext(), "加载视频数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
                }
            }
        }).start();
    }

    private void saveVideoChanges() {
        String title = etTitle.getText().toString().trim();
        String description = etDescription.getText().toString().trim();
        String tags = etTags.getText().toString().trim();

        // 验证输入
        if (TextUtils.isEmpty(title)) {
            Toast.makeText(getContext(), "请输入标题", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(description)) {
            Toast.makeText(getContext(), "请输入描述", Toast.LENGTH_SHORT).show();
            return;
        }

        // 验证标签格式
        if (!validateTags(tags)) {
            Toast.makeText(getContext(), "标签格式不正确，请使用#开头，多个标签用逗号分隔", Toast.LENGTH_SHORT).show();
            return;
        }

        // 更新视频信息
        new Thread(() -> {
            try {
                boolean success = dbHelper.updateVideoInfo(videoId, title, description, tags);
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        if (success) {
                            Toast.makeText(getContext(), "修改成功", Toast.LENGTH_SHORT).show();

                            // 通知监听器
                            if (onVideoUpdatedListener != null) {
                                onVideoUpdatedListener.onVideoUpdated();
                            }

                            // 通知MainActivity刷新其他页面
                            if (mainActivity != null) {
                                mainActivity.refreshHomePage();
                                mainActivity.refreshMessageAndSelfPages();
                            }

                            dismiss();
                        } else {
                            Toast.makeText(getContext(), "修改失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() ->
                            Toast.makeText(getContext(), "修改失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
                }
            }
        }).start();
    }

    private boolean validateTags(String tags) {
        if (TextUtils.isEmpty(tags)) {
            return true; // 允许空标签
        }

        // 检查标签长度
        if (tags.length() > 20) {
            return false;
        }

        // 简单的标签格式验证：以#开头，多个标签用逗号分隔
        String[] tagArray = tags.split(",");
        for (String tag : tagArray) {
            String trimmedTag = tag.trim();
            if (!trimmedTag.isEmpty() && !trimmedTag.startsWith("#")) {
                return false;
            }
        }

        return true;
    }
}